package com.csaba.util;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Logger;

/**
 * This class provides methods to load language specific texts from property files. 
 * To get a text the caller always has to specify a "namespace" that defines where
 * to find property file, that will be loaded from the package of namespace object.
 * <p>The class provides options to resolve dynamic texts as well, containing values
 * by using the java.text.MessageFormat class for formatting. For the syntax of
 * parametrized texts see Java doc of MessageFormat.
 * <p>The locale is identified by the I18NProviderFactory class. By default the default
 * locale is used to load property file. For further possibilities see {@link I18NProviderFactory}.  
 * 
 * @author gyenes
 *
 */
public class I18N
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	/**
	 * Returns the text identified by the key from the packge of the namespace object.
	 * The method first try to load the &lt;namespace.className&gt;.&lt;key&gt; key. If it
	 * is not found, then the key is used as identifier alone.   
	 * 
	 * @param namespace
	 * @param key
	 * @return
	 */
	public static String getString( final Object namespace, final String key )
	{
		final ResourceBundle bundle = I18NProviderFactory.getProvider().getBundle(namespace);
		if ( bundle == null )
		{
			return key;
		}

		final String className = namespace.getClass().getSimpleName();

		try
		{
			return bundle.getString(className + '.' + key);
		}
		catch ( final MissingResourceException e )
		{
			try
			{
				return bundle.getString(key);
			}
			catch ( final MissingResourceException e2 )
			{
				logger.finest("Cannot find resource for propery " + key + " in package "
						+ namespace.getClass().getName());
				return key;
			}
		}
	}

	public static String getString( final Object namespace, final String key, final Object... arguments )
	{
		final String message = getString(namespace, key);
		return MessageFormat.format(message, arguments);
	}
}
